package com.kqb.sgcommon.ds.translation;

import com.kqb.sgcommon.ds.annotation.DictTranslate;
import com.kqb.sgcommon.ds.model.Dict;
import com.kqb.sgcommon.ds.service.DictService;
import jakarta.annotation.Resource;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

/**
 * @author 杉果树皮
 */

@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
@Component
public class DictTranslateInterceptor implements Interceptor {

    @Resource
    @Lazy
    private DictService dictService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof List) {
            for (Object entity : (List<?>) result) {
                translateEntity(entity);
            }

        } else {
            translateEntity(result);
        }
        return result;
    }

    private void translateEntity(Object entity) throws IllegalAccessException {
        if (entity == null) {
            return;
        }
        Class<?> clazz = entity.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.isAnnotationPresent(DictTranslate.class)) {
                DictTranslate annotation = field.getAnnotation(DictTranslate.class);
                String dictType = annotation.dictType();
                String valueTo = annotation.valueTo();
                // 获取字段值（关联 ID）
                field.setAccessible(true);
                Object o = field.get(entity);
                String dictName;
                if (o != null) {
                    //如果不设置就根据值 id 去查询字典 得到字典名称
                    if ("NONE".equals(dictType)) {
                        int id = (int) o;
                        dictName = dictService.getById(id).getDictName();
                    } else {
                        //如果设置就根据值 code 去查询字典
                        String dictCode = (String) o;
                        dictName = dictService.getDictByCodeAndType(dictCode, dictType).getDictName();
                    }
                    // 将名称设置到对应的字段中
                    Field fieldByName = getFieldByName(clazz, valueTo);
                    if (fieldByName != null) {
                        fieldByName.setAccessible(true);
                        fieldByName.set(entity, dictName);
                    }
                }
            }
        }

    }

    private Field getFieldByName(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            return null;
        }
    }
}
